<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.9
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############

if(!isset($block)){
	if(post('parent_block_id', get('blockId'))!='' && post('page_id', get('pageId'))!=''){
		$block = JFX_Block::getBlockById(post('parent_block_id', get('blockId')), post('page_id', get('pageId')));
	}
}

assert($block instanceof JFX_Block);


$blockDetails = $block->details;
$blockDetails['title'] = JFX_Block::getTitleById($block->id, $block->pageid, '', $block->workspaceid);

$SMARTY->assign('blockDetails', $blockDetails);

if(!Antz_IntelliForm::submitted('insert-block')){
	if(count($_POST)>0){
		
		$showForm = true;
		
		// confirming the insert
		$formFields = array(
			array(
				'type' => 'hidden',
				'name' => 'parent_block_id',
				'value' => post('parent_block_id', $block->id)
			),
			array(
				'type' => 'hidden',
				'name' => 'page_id',
				'value' => post('page_id', $block->id)
			)
		);

		$SMARTY->assign('type', 'default');

		if(post('new_block_id')!=''){
			// inserting a template
			$SMARTY->assign('type', 'template');
			$SMARTY->assign('newBlockTitle', JFX_Block::getTitleById(post('new_block_id')));

			$formFields[] = array(
				'type' => 'hidden',
				'name' => 'new_block_id',
				'value' => post('new_block_id')
			);

		}else if(post('module')!='' && post('action')!=''){
			$SMARTY->assign('type', 'module');
			$SMARTY->assign('moduleKey', post('module'));
			$SMARTY->assign('moduleAction', post('action'));
			$module = JFX_Module::getInstance(post('module'));
			$SMARTY->assign('contentTypeName', $module->getContentTypeName(post('action')));


			$formFields[] = array(
				'type' => 'hidden',
				'name' => 'module',
				'value' => post('module')
			);
			$formFields[] = array(
				'type' => 'hidden',
				'name' => 'action',
				'value' => post('action')
			);
			
		}else{
			$showForm = false;
		}
		
		if($showForm){
			$formFields[] = array(
				'id' => 'jfx-insert-form-submit',
				'type' => 'button',
				'value' => $this->lang('confirm_insert_block')
			);



			$insertForm = JFX::makeRapidForm($formFields, $this->lang('add_block_legend'), 'insert-block');
			$insertForm->setId('jfx-insert-form');

			$SMARTY->assign('insertForm', $insertForm);

			echo $SMARTY->fetch($CONFIG->templatesDir.'/admin/ajax/insert-block.parent-summary.tpl');
			echo $SMARTY->fetch($CONFIG->templatesDir.'/admin/ajax/insert-block.form.tpl');

			$js = <<<JS
<script type="text/javascript" language="JavaScript">
$(document).ready(function(){
$('#jfx-insert-form-submit').click(function(){
	var evalFunc = function(json){
		json = JSON.parse(json);
		$('#jfx-insert-block-parameters').html(json._MAIN);
	}
	$.post('{$CONFIG->adminUrl}/ajax/insert-block/?JFXGetAjaxContent=1', $('#jfx-insert-form').serialize(), evalFunc);

});
});
</script>
JS;
			echo $js;
			
		}


	}
}else{
	// let's insert this block
	if(post('new_block_id')!='' && post('page_id')!=''){
		$block->addTemplateBlock(post('new_block_id'), post('page_id'));
		
	}else if(post('module')!='' && post('action')!=''){
		$block->addModuleBlock(post('module'), post('action'), post('page_id'));

	}


	echo $this->getRebuildPage();

}


















if(!count($_POST)>0){

	$templatePageid = $SETTINGS->get('template_page_id');
	$templates = array();
	$tps = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}blocks WHERE page_id = '{$templatePageid}' AND is_template = 1 AND workspace_id = 1 AND page_parent = 1");
	foreach($tps as $k=>$v){
		$loopBlock = JFX_Block::getBlockById($v['id'], $templatePageid, $v['workspace_id'], true, true);
		$details = $loopBlock->getDetails();
		if($DB->countRows($CONFIG->dbprefix.'blocks', "page_id='{$block->pageid}' AND template_id = '{$loopBlock->id}' AND workspace_id = '{$block->workspaceid}'")>0){
			// already has block like this on this page
			unset($tps[$k]);
			continue;
		}
		$tps[$k] = $loopBlock;
		
	}


	// sort by title
	$newtps = array();
	foreach($tps as $v){
		$newtps[$v->title] = $v;
	}

	ksort($newtps);
	foreach($newtps as $v){
		$templates[] = array(
			'title' => $v->title,
			'id' => $v->id
		);
	}


	$modules = array();
	$mods = JFX_Module::getInstalledModules();
	$count = 0;
	foreach($mods as $k=>$v){
		$module = JFX::registry('JFX_Module_'.$v['keyname']);
		$actions = $module->getBlockActions();
		if(!is_array($actions) || count($actions)==0) continue;
		$modules[$count] = array(
			'keyname' => $module->keyname,
			'title' => $module->getTitle(),
			'actions' => array()
		);
		foreach($actions as $key=>$value){
			$modules[$count]['actions'][] = array(
				'title' => $value['title'],
				'keyname' => $value['keyname']
				//'description' => trim((string) $value['description'])
			);
		}
		$count++;
	}


	$pageId = preg_replace('/[^0-9]/', '', $block->pageid);



	$loopBlock = new JFX_Block;
	$insertMenu = '
	<div id="jfx-insert-block-parameters">'
		.$SMARTY->fetch($CONFIG->templatesDir.'/admin/ajax/insert-block.parent-summary.tpl')
	.'</div>
	<div class="jfx-insert-menu">
	<h2>'.$this->lang('insert_block_title').'</h2>
	<ul class="insert-menu-treeview">
	<div id="insert-menu-close-button"><img src="'.$CONFIG->imageUrl.'/admin/layout/close-normal.png" alt="Close" /></div>
';
	if(count($templates)){

		$insertMenu .= '

		<li class="templates">'.$this->lang('templates').'
		<ul>';
		foreach($templates as $k=>$v){
			$insertMenu .= '<li>
			<a href="javascript: void(null)" class="jfx-insert-template"
		xml:parent_block_id="'.$block->id.'" xml:new_block_id="'.$v['id'].'" xml:page_id="'.$pageId.'">'
			.$v['title'].'</a></li>';

		}

		$insertMenu .= '</ul></li>';

	}

	$insertMenu .= '
	
	<li>'.$this->lang('modules').'
	<ul>';

	foreach($modules as $k=>$module){
		$insertMenu .= '<li>'.$module['title'].'
	<ul>';
		foreach($module['actions'] as $k2=>$action){
			$insertMenu .= '<li><a href="javascript: void(null)" class="jfx-insert-module"
				xml:parent_block_id="'.$block->id.'" xml:to_module="'.$module['keyname'].'" xml:to_action="'.$action['keyname'].'" xml:page_id="'.$pageId.'">'
			.$action['title'].'</a></li>';
		}
	$insertMenu .= '</ul>
	</li>';
	}

	$insertMenu .= '</ul>
	</li>
	</ul>
	</div>
	';



	echo $insertMenu;

	$js = <<<JS
<script type="text/javascript" language="JavaScript">
	$('.insert-menu-treeview').treeview({

		   persist: "location",
			collapsed: true,
			unique: true

	});


	$('.jfx-insert-template').click(function(){
		var evalFunction = function(text){
			$('#jfx-insert-block-parameters').html(text);
		}
		var url = JFXConfig.adminUrl+'/ajax/insert-block';
		var parms = {
			'parent_block_id' : $(this).attr('xml:parent_block_id'),
			'new_block_id' : $(this).attr('xml:new_block_id'),
			'page_id' : $(this).attr('xml:page_id')
		};
		$.post(url, parms, evalFunction);

	});

	$('.jfx-insert-module').click(function(){
		var evalFunction = function(text){
			console.log(text);
			$('#jfx-insert-block-parameters').html(text);
		}
		var url = JFXConfig.adminUrl+'/ajax/insert-block';
		var parms = {
			'parent_block_id' : $(this).attr('xml:parent_block_id'),
			'module' : $(this).attr('xml:to_module'),
			'action' : $(this).attr('xml:to_action'),
			'page_id' : $(this).attr('xml:page_id')
		};
		$.post(url, parms, evalFunction);

	});




</script>
JS;

	echo $js;
}